package com.yxp.offer;

/**
 * @author : yang.xp
 * @date : 2021/8/25 9:48
 * @description : 剑指 Offer 57. 和为s的两个数字
 */
public class Problem57_1 {

    public static void main(String[] args) {
        Problem57_1 problem571 = new Problem57_1();
        int[] ints = problem571.twoSum(new int[]{10, 26, 30, 31, 47, 60}, 40);
        for (int i = 0; i < ints.length; i++) {
            System.out.println(ints[i]);
        }
    }
//    这种方法超时了
//    public int[] twoSum(int[] nums, int target) {
//        int[] result = new int[2];
//        goto:
//        for (int firstIndex = 0; firstIndex < nums.length - 1; firstIndex++) {
//            for (int secondIndex = firstIndex; secondIndex < nums.length; secondIndex++) {
//                if (nums[firstIndex] >= target) {
//                    break goto;
//                }
//                if (nums[secondIndex] >= target) {
//                    break;
//                }
//                if (nums[firstIndex] + nums[secondIndex] == target) {
//                    result[0] = nums[firstIndex];
//                    result[1] = nums[secondIndex];
//                    break goto;
//                }
//            }
//
//        }
//        return result;
//    }

    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        int firstIndex = 0, lastIndex = nums.length - 1;

        while (firstIndex < lastIndex) {
            int temp = nums[firstIndex] + nums[lastIndex];
            if (temp < target) {
                firstIndex++;
            } else if (temp > target) {
                lastIndex--;
            } else {
                result[0] = nums[firstIndex];
                result[1] = nums[lastIndex];
                return result;
            }

        }
        return result;
    }
}
